package com.chuantou.yuba.ui;

import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.chuantou.yuba.R;
import com.chuantou.yuba.adapter.ImageAdapter;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.FishingPlaceDetailDataTO;
import com.chuantou.yuba.api.to.FishingPlaceTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.widget.ChildViewPager;
import com.chuantou.yuba.ui.widget.LoadingView;
import com.chuantou.yuba.ui.widget.SharePopup;
import com.chuantou.yuba.ui.widget.LoadingView.Style;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.UiUtil;
import com.viewpagerindicator.IconPageIndicator;

public class FishingPlaceDetailActivity extends BaseActionBarActivity implements OnClickListener {
	private FishingPlaceTO mPlaceTO;
	private long mPlaceId;
	private TextView mContentView;
	private TextView mAddressView;
	private TextView mContactView;
	private TextView mPhoneView;
	private TextView mFeatureView;
	private TextView mTypeView;
	private TextView mCostView;
	private ChildViewPager mImageViewPager;
	private IconPageIndicator mIconPageIndicator;
	private ImageAdapter mImageAdapter;
	private View mDetailLayout;
	private LoadingView mLoadingView;
	private boolean mFavorited = false;
	private SharePopup mSharePopup;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mPlaceId = getIntent().getLongExtra(Constants.EXTRA_DATA, -1);
		setContentView(R.layout.fishing_place_detail);
		setupViews();
		setTitle(R.string.fishing_place_detail);
		requestFromNetwork();
	}

	private void setupViews() {
		findViewById(R.id.address_layout).setOnClickListener(this);
		findViewById(R.id.phone_layout).setOnClickListener(this);
		mContentView = (TextView) findViewById(R.id.content);
		mAddressView = (TextView) findViewById(R.id.address);
		mTypeView = (TextView) findViewById(R.id.type);
		mContactView = (TextView) findViewById(R.id.contact);
		mPhoneView = (TextView) findViewById(R.id.telephone);
		mFeatureView = (TextView) findViewById(R.id.feature);
		mImageViewPager = (ChildViewPager) findViewById(R.id.viewpager);
		mIconPageIndicator = (IconPageIndicator) findViewById(R.id.indicator);
		mImageAdapter = new ImageAdapter(getApplicationContext());
		mImageViewPager.setAdapter(mImageAdapter);
		mIconPageIndicator.setViewPager(mImageViewPager);
		mDetailLayout = findViewById(R.id.detail_layout);
		mTypeView = (TextView) findViewById(R.id.type);
		mLoadingView = (LoadingView) findViewById(R.id.loading_view);
		mCostView = (TextView) findViewById(R.id.cost);
		mLoadingView.setOnRetryListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				requestFromNetwork();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (mPlaceTO != null) {
			getMenuInflater().inflate(R.menu.menu_fav, menu);
			MenuItem menuItem = menu.findItem(R.id.menu_fav);
			if (mFavorited) {
				menuItem.setTitle(R.string.remove_favorite);
			} else {
				menuItem.setTitle(R.string.add_favorite);
			}
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_fav:
			operateFavorite(!mFavorited);
			return true;
		case R.id.menu_share:
			if (!UiUtil.isFastDoubleClick()) {
				if (mSharePopup != null && mSharePopup.isShowing())
					return true;
				mSharePopup = new SharePopup(this);
				ViewGroup decor = (ViewGroup) getWindow().getDecorView();
				mSharePopup.showAtLocation(decor, Gravity.BOTTOM, 0, 0);
			}
			return true;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void requestFromNetwork() {
		mLoadingView.setStyle(Style.LOADING, null);
		String url = UriHelper.getFishingPlaceDetailUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		AccountManager accountManager = AccountManager.getInstance(getApplicationContext());
		if (accountManager.isLogined()) {
			UserTO user = accountManager.getUserTO();
			params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
		}
		params.put(UriHelper.PARAMS_ID, String.valueOf(mPlaceId));
		GsonRequest<FishingPlaceDetailDataTO> request = new GsonRequest<FishingPlaceDetailDataTO>(Method.POST, url, new Listener<FishingPlaceDetailDataTO>() {

			@Override
			public void onResponse(FishingPlaceDetailDataTO response) {
				if (!hasDestroyed()) {
					if (response != null) {
						FishingPlaceTO place = response.getPlace();
						if (place == null) {
							mLoadingView.setStyle(Style.ERROR, null);
						} else {
							mFavorited = response.isFaved();
							mPlaceTO = place;
							mLoadingView.setVisibility(View.GONE);
							mDetailLayout.setVisibility(View.VISIBLE);
							supportInvalidateOptionsMenu();
							setDetail(mPlaceTO);
						}
					} else {
						mLoadingView.setStyle(Style.ERROR, null);
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (!hasDestroyed()) {
					mLoadingView.setStyle(Style.ERROR, null);
				}
			}
		}, params, FishingPlaceDetailDataTO.class);
		RequestManager.startRequest(getApplicationContext(), request);
	}

	/**
	 * 操作收藏
	 * 
	 * @param isAdd
	 */
	private void operateFavorite(final boolean isAdd) {
		final Context context = getApplicationContext();
		// 先判断是否已经登录
		AccountManager manager = AccountManager.getInstance(context);
		if (manager.isLogined()) {
			UserTO user = manager.getUserTO();
			if (user.isExpired()) {
				Toast.makeText(context, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
				LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
			} else {
				String requestUrl = UriHelper.getOperateFavoriteUrl();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(UriHelper.PARAMS_ACTION, isAdd ? "add" : "del");
				params.put(UriHelper.PARAMS_TOKEN, user.getToken());
				params.put(UriHelper.PARAMS_TYPE, "place");
				params.put(UriHelper.PARAMS_ID, String.valueOf(mPlaceId));
				params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
				GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, requestUrl, new Listener<BaseTO>() {

					@Override
					public void onResponse(BaseTO response) {
						if (!hasDestroyed()) {
							if (response != null) {
								if (response.isSuccess()) {
									Toast.makeText(context, R.string.operate_success, Toast.LENGTH_SHORT).show();
									mFavorited = isAdd ? true : false;
									supportInvalidateOptionsMenu();
								} else {
									if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
										Toast.makeText(context, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
										LoginActivity.start(FishingPlaceDetailActivity.this, -1, LoginActivity.ACTION_RETURN);
									} else {
										Toast.makeText(context, R.string.operate_failed, Toast.LENGTH_SHORT).show();
									}
								}
							} else {
								Toast.makeText(context, R.string.operate_failed, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (!hasDestroyed()) {
							Toast.makeText(context, R.string.request_error, Toast.LENGTH_SHORT).show();
						}
					}
				}, params, BaseTO.class);
				RequestManager.startRequest(context, request);
			}
		} else {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
		}
	}

	private void setDetail(FishingPlaceTO place) {
		mContentView.setText(place.getContent());
		mAddressView.setText(place.getAddress());
		mTypeView.setText(place.getPlaceType());
		mContactView.setText(place.getContact());
		mPhoneView.setText(place.getPhone());
		mFeatureView.setText(place.getFeature());
		mCostView.setText(place.getPriceType());
		mImageAdapter.addImage(place.getImages());
		mImageAdapter.notifyDataSetChanged();
		mIconPageIndicator.notifyDataSetChanged();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.address_layout: {
			String location = mPlaceTO.getLocation();
			String lat = "0";
			String lng = "0";
			if (!TextUtils.isEmpty(location) && location.contains(",")) {
				String[] array = location.split(",");
				lat = array[1];
				lng = array[0];
			}
			String point = lat + "," + lng;
			String label = mPlaceTO.getAddress();
			String uriBegin = "geo:" + point;
			String query = point + "(" + label + ")";
			String encodedQuery = Uri.encode(query);
			String uriString = uriBegin + "?q=" + encodedQuery;
			Uri uri = Uri.parse(uriString);
			Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri);
			if (UiUtil.isIntentAvailable(this, intent)) {
				startActivity(intent);
			} else {
				Toast.makeText(this, R.string.no_navi_app_installed, Toast.LENGTH_SHORT).show();
			}
		}
			break;
		case R.id.phone_layout: {
			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_DIAL);
			intent.setData(Uri.parse("tel:" + mPlaceTO.getPhone()));
			startActivity(intent);
		}
			break;
		default:
			break;
		}
	}

}
